﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Expression.Blend.SampleData.SampleDataSource;
using Twilio;
using Windows.Foundation;
using Windows.Graphics.Display;
using Windows.Security.Authentication.Web;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using RobertMcLaws.TwilioForWin8.Helpers;

namespace RobertMcLaws.TwilioForWin8
{
    public sealed partial class MainPage
    {

        #region Private Members

        private DisplayPropertiesEventHandler _displayHandler;
        private TypedEventHandler<ApplicationLayout, ApplicationLayoutChangedEventArgs> _layoutHandler;

        #endregion

        #region Page Lifecycle

        public MainPage()
        {
            InitializeComponent();
        }

        // View state management for switching among Full, Fill, Snapped, and Portrait states
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (_displayHandler == null)
            {
                _displayHandler = Page_OrientationChanged;
                _layoutHandler = Page_LayoutChanged;
            }
            DisplayProperties.OrientationChanged += _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged += _layoutHandler;
            SetCurrentOrientation(this);


            //RWM: This sucks, and is not the 100% right way to do it in WinRT, but it works. 
            //     Needs to be fixed to use Async/Await
            StatusPanel.Visibility = Visibility.Visible;
            var baseUri = new Uri(this.BaseUri.ToString());
            Task.Run(() => LoadData(baseUri)).ContinueWith((t) => {
                if (t.IsCompleted)
                {
                    Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.High, (s, a) =>
                    {
                        StatusPanel.Visibility = Visibility.Collapsed;
                        RobertMcLaws.TwilioForWin8.App.ShowGroupedCollection();
                    }, this, null);
                }
            });

        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            DisplayProperties.OrientationChanged -= _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged -= _layoutHandler;
        }

        private void Page_LayoutChanged(object sender, ApplicationLayoutChangedEventArgs e)
        {
            SetCurrentOrientation(this);
        }

        private void Page_OrientationChanged(object sender)
        {
            SetCurrentOrientation(this);
        }

        private void SetCurrentOrientation(Control viewStateAwareControl)
        {
            VisualStateManager.GoToState(viewStateAwareControl, this.GetViewState(), false);
        }

        private String GetViewState()
        {
            var orientation = DisplayProperties.CurrentOrientation;
            if (orientation == DisplayOrientations.Portrait ||
                orientation == DisplayOrientations.PortraitFlipped) return "Portrait";
            var layout = ApplicationLayout.Value;
            if (layout == ApplicationLayoutState.Filled) return "Fill";
            if (layout == ApplicationLayoutState.Snapped) return "Snapped";
            return "Full";
        }

        #endregion

        private void LoadData(Uri baseUri)
        {

            string accountSid = "";
            string apiKey = "";

            var results = new TwilioDataSource(baseUri);

            var client = new TwilioRestClient(accountSid, apiKey);
            var cr = client.ListCalls();

            if (cr!= null)
            {
                results.AddCollection("Calls", "", baseUri, "", "Here are the last 50 phone calls for your account.");
                foreach (var call in cr.Calls)
                {
                    results.AddItem(call.From, call.StartTime.Value.ToString(), baseUri, "", call.ToSummaryString());
                }
            }
            RobertMcLaws.TwilioForWin8.App.SampleData = results;
            RobertMcLaws.TwilioForWin8.App.TwilioClient = client;

        }


    }
}
